import { MutableRefObject } from 'react';
import { extendApi } from '@inbiz/utils';
import type { IProps } from './index';
import { getDocumentInfoByFile, getDocumentInfoByFolder } from './service';

export default extendApi((_events: MutableRefObject<IProps['callBackEvents']>, props: IProps) => {
  return {
    getText: () => {
      return props.value.map((item: any) => item.name).join(',');
    },
    getSaveData: () => {
      if (props.mode === 'SelectFile') {
        return {
          value: props.value?.map((item: any) => item.fileid || item.folderid).join(','),
          childData:
            props.storageConfig && props.childModelConfig
              ? {
                  controlId: props.controlId,
                  modelKey: props.storageConfig?.business,
                  datas: [
                    ...(props.value ?? []).map((item: any) => {
                      return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                        pre[next.modelAttr] = item[next.componentAttr];
                        pre['_opt'] = 'add';
                        return pre;
                      }, {});
                    }),
                    {
                      _opt: 'del',
                    },
                  ],
                }
              : undefined,
        };
      } else {
        return {
          value: props.value?.map((item: any) => item.folderid || item.folderid).join(','),
          childData:
            props.storageConfig && props.childModelConfig
              ? {
                  controlId: props.controlId,
                  modelKey: props.storageConfig?.business,
                  datas: [
                    ...(props.value ?? []).map((item: any) => {
                      return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                        pre[next.modelAttr] = item[next.componentAttr];
                        pre['_opt'] = 'add';
                        return pre;
                      }, {});
                    }),
                    {
                      _opt: 'del',
                    },
                  ],
                }
              : undefined,
        };
      }
    },
    setMetaData: async (data: string | string[]) => {
      let isMultipleData:boolean;
      if (Array.isArray(data)) {
        isMultipleData = data?.length > 1
      } else if(data!=""&&data!=null&&data!=undefined) {
        isMultipleData = data.includes(',');
      }
      if(!props.multiple && isMultipleData) {
        console.error('单选模式下仅支持设置一个文件!');
        return;
      }
      const { mode, value } = props;
      const allValue = value ? [...value] : [];
      let allData = typeof data === 'string' ? data : data?.join(',');
      if (mode === 'SelectFile') {
        const allValueIds =
          value?.map((item: any) => {
            return item.fileid;
          }) || [];
        const res = await getDocumentInfoByFile(allData, props);
        const resultData = res.map((item: any) => {
          return { ...item, name: item.filename, key: item.fileid };
        });
        const pushData = resultData.filter((item: any) => {
          return !allValueIds?.includes(item.fileid);
        });
        allValue.push(...pushData);
        props?.onChange([...allValue]);
        return resultData;
      } else {
        const allValueIds =
          value?.map((item: any) => {
            return item.folderid;
          }) || [];
        const res = await getDocumentInfoByFolder(allData, props);
        let resultData = res.map((item: any) => {
          return { ...item, name: item.foldername, key: item.folderid };
        });
        let pushData = resultData.filter((item: any) => {
          return !allValueIds?.includes(item.folderid);
        });
        allValue.push(...pushData);
        props?.onChange([...allValue]);
        return resultData;
      }
    },
  };
});
